package com.zzyl.nursing.service.impl;

import cn.hutool.core.collection.ListUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.RandomUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zzyl.framework.web.service.TokenService;
import com.zzyl.nursing.domain.FamilyMember;
import com.zzyl.nursing.dto.UserLoginRequestDto;
import com.zzyl.nursing.mapper.FamilyMemberMapper;
import com.zzyl.nursing.service.IFamilyMemberService;
import com.zzyl.nursing.service.WechatService;
import com.zzyl.nursing.vo.LoginVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;

/**
 * 老人家属Service业务层处理
 *
 * @author ruoyi
 * @date 2025-09-13
 */
@Service
public class FamilyMemberServiceImpl extends ServiceImpl<FamilyMemberMapper, FamilyMember> implements IFamilyMemberService {

    static List<String> DEFAULT_NICKNAME_PREFIX = ListUtil.of(
            "生活更美好",
            "大桔大利",
            "日富一日",
            "好柿开花",
            "柿柿如意",
            "一椰暴富",
            "大柚所为",
            "杨梅吐气",
            "天生荔枝"
    );

    @Autowired
    private FamilyMemberMapper familyMemberMapper;
    @Autowired
    private WechatService wechatService;
    @Autowired
    private TokenService tokenService;

    /**
     * 微信小程序端用户登录
     *
     * @param userLoginRequestDto
     * @return
     */
    @Override
    public LoginVo login(UserLoginRequestDto userLoginRequestDto) {
        // 1. 调用微信接口获取openId和phone
        String openId = wechatService.getOpenId(userLoginRequestDto.getCode());
        String phone = wechatService.getPhoneNumber(userLoginRequestDto.getPhoneCode());
        // 2. 通过openId查询数据库 判断用户是否在数据库中存在（不存在则新增）
        FamilyMember familyMember = lambdaQuery().eq(FamilyMember::getOpenId, openId)
                .one();
        // 3.  新用户则构建用户对象 填充数据（openId 和 phone）
        if (ObjectUtil.isEmpty(familyMember)) {
            familyMember = new FamilyMember();
            familyMember.setOpenId(openId);
            familyMember.setPhone(phone);
        }
        // 4. 新增或修改用户 修改用户信息（手机号改变的情况） 新增生成用户昵称
        saveOrUpdate(familyMember, phone);
        // 5. 生成token
        Map<String, Object> map = Map.of("userId", familyMember.getId(), "nickName", familyMember.getName());
        String token = tokenService.createToken(map);
        // 6. 返回vo
        return LoginVo.of(token, familyMember.getName());
    }

    private void saveOrUpdate(FamilyMember familyMember, String phone) {
        //   String prefix = DEFAULT_NICKNAME_PREFIX.get(RandomUtil.randomInt(0, DEFAULT_NICKNAME_PREFIX.size()));
        String prefix = RandomUtil.randomEle(DEFAULT_NICKNAME_PREFIX);
        String nickName = prefix + phone.substring(7);
        if (ObjectUtil.isEmpty(familyMember.getId())) {
            familyMember.setName(nickName);
            save(familyMember);
            return;
        }
        if (!phone.equals(familyMember.getPhone())) {
            familyMember.setPhone(phone);
            updateById(familyMember);
        }
    }

}
